package youquan;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import entity.Feed;
import entity.Statement;
import entity.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * author: zhangxiong
 * created on: 17-2-15 下午10:52
 * description:
 */
public class HttpAccess {

    private static final String TAG = "HttpAccess";

    //token值
    private String token = "";

    //公共的内存数据存储
    /**
     * 修改人：王龙飞
     */
    public static Map<String, String> map = new HashMap<String, String>();
    public static List<Map<String, String>> list = new ArrayList<Map<String, String>>();


    public static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    //authorization 前缀
    private static final String AUTH_CONSTANT = "Bearer ";

    private YouQuanHttpManager youQuanHttpManager = YouQuanHttpManager.getmInstance();

    private int errorCode = YouQuanService.OP_SUCCESS;

    int getLatestErrorCode() {
        return errorCode;
    }

    private String errorMsg = "未知错误";

    String getLatestErrorMsg() {
        return errorMsg;
    }

    //用户登录后返回用户对象
    public User userLogin(List<Param> params) {
        //清空
        User user = null;
        //登录
//        youQuanHttpManager.post(YouQuanConstants.loginUrl, params, new YouQuanHttpManager.HttpCallBack() {
//            @Override
//            public void onResponse(JSONObject jsonObject) {
//                //parseLoginJson(loginJson);
//                System.out.println(jsonObject.toJSONString());
//            }
//
//            @Override
//            public void onFailure(String errorMsg) {
//
//            }
//        });

        String loginJson = youQuanHttpManager.post(YouQuanConstants.loginUrl, params);
        int result = parseLoginJson(loginJson);
        if (result != YouQuanService.OP_SUCCESS) {
            return null;
        }

        Param auth = new Param("Authorization", AUTH_CONSTANT + this.getToken());
        String personJson = youQuanHttpManager.get(YouQuanConstants.userMeUrl, auth);
        result = parsePersonalJson(personJson);
        if (result != YouQuanService.OP_SUCCESS) {
            return null;
        }

        user = new User(
                Long.parseLong(map.get("id")),
                map.get("username"),
                map.get("userPhone"),
                "2406080330",
                map.get("name"),
                map.get("pinyinName"),
                map.get("iconUri"),
                map.get("bgImgUri"),
                "西安 中国",
                "computer;software;art",
                map.get("selfIntroduction"),
                Long.parseLong(map.get("lng")),
                Long.parseLong(map.get("lat")),
                System.currentTimeMillis(),
                User.USER_TYPE_ME,
                0);

        return user;
    }

    public List<User> syncContactList(String username) {

        User user = null;
        Param auth = new Param("Authorization", AUTH_CONSTANT + this.getToken());
        String usersJson = youQuanHttpManager.get(YouQuanConstants.usersUrl, auth);
        int result = parseContactsJson(usersJson);
        if (result != YouQuanService.OP_SUCCESS) {
            return null;
        }
        List<User> contactList = new ArrayList<User>();
        for (Map<String, String> map : list) {
            user = new User(
                    Long.parseLong(map.get("id")),
                    map.get("username"),
                    map.get("userPhone"),
                    "2406080330",
                    map.get("name"),
                    map.get("pinyinName"),
                    map.get("iconUri"),
                    map.get("bgImgUri"),
                    "西安 中国",
                    "computer;software;art",
                    map.get("selfIntroduction"),
                    Long.parseLong(map.get("lng")),
                    Long.parseLong(map.get("lat")),
                    System.currentTimeMillis(),
                    User.USER_TYPE_CONTACT,
                    0);
            contactList.add(user);
        }

        errorCode = YouQuanService.OP_SUCCESS;
        return contactList;
    }

    public List<Feed> syncFeeds(String username, List<User> contactList, User curUser) {
        long now = System.currentTimeMillis();

        Param auth = new Param("Authorization", AUTH_CONSTANT + this.getToken());
        String feedsJson = youQuanHttpManager.get(YouQuanConstants.feedsUrl, auth);
        int result = parseFeedsJson(feedsJson);
        if (result != YouQuanService.OP_SUCCESS) {
            return null;
        }
        List<Feed> feedList = new ArrayList<Feed>();
        Feed feed = null;
        for (Map<String, String> map : list) {
            feed = new Feed(
                    null,
                    "没有找到",
                    map.get("content"),
                    Long.parseLong(map.get("publishTime")),
                    Long.parseLong(map.get("publishTime")),
                    Long.parseLong(map.get("ownerId")),
                    map.get("imgUri_1"),
                    map.get("imgUri_2"),
                    map.get("imgUri_3"),
                    map.get("imgUri_4"),
                    map.get("imgUri_5"),
                    map.get("imgUri_6"),
                    map.get("imgUri_7"),
                    map.get("imgUri_8"),
                    map.get("imgUri_9"),
                    Double.parseDouble(map.get("lng")),
                    Double.parseDouble(map.get("lat")),
                    map.get("locationStr"));
            feedList.add(feed);
        }
        errorCode = YouQuanService.OP_SUCCESS;
        return feedList;
    }

    public List<Statement> retrieveNewStatements(String username) {

        Statement message = null;
        Param auth = new Param("Authorization", AUTH_CONSTANT + this.getToken());
        String messagesJson = youQuanHttpManager.get(YouQuanConstants.statementsUrl, auth);
        int result = parseStatementsJson(messagesJson);
        if (result != YouQuanService.OP_SUCCESS) {
            return null;
        }
        List<Statement> messeageList = new ArrayList<Statement>();

        for (Map<String, String> map : list) {
            message = new Statement();


            messeageList.add(message);
        }



        errorCode = YouQuanService.OP_SUCCESS;
        return messeageList;
    }

    private int parseStatementsJson(String messagesJson) {
        map.clear();
        if (YouQuanStringHelper.isEmptyOrNull(messagesJson)) {
            errorCode = YouQuanService.OP_NETWORK_ERR;
            errorMsg = "网络错误";
            return YouQuanService.OP_NETWORK_ERR;
        }

        JSONArray json = JSON.parseArray(messagesJson);
        if (null == json) {
            errorCode = YouQuanService.OP_SERVER_DENY_ERR;
            errorMsg = "消息获取失败！";
            return YouQuanService.OP_SERVER_DENY_ERR;
        }

        for(int i = 0;i<json.size();i++){
            JSONObject message = json.getJSONObject(i);
            map.put("chatId",message.getString("id"));

            SimpleDateFormat sf = new SimpleDateFormat(TIME_FORMAT, Locale.CHINA);
            Long lastRefefreshTime;
            try {
                lastRefefreshTime = sf.parse(message.getString("createdAt")).getTime();
            } catch (ParseException e) {
                lastRefefreshTime = 0L;
            }
            map.put("time", lastRefefreshTime.toString());
            map.put("userId",message.getJSONObject("sender").getString("id"));
            map.put("iconUri",message.getJSONObject("sender").getString("avatar"));
            map.put("contentStr",message.getString("content"));
            map.put("contentType",message.getString("type"));
            map.put("state",message.getString("status"));
            map.put("isOwn",message.getInteger("receiver").toString());

        }

        return YouQuanService.OP_SUCCESS;
    }

    private int parseFeedsJson(String feedsJson) {
        list.clear();
        if (YouQuanStringHelper.isEmptyOrNull(feedsJson)) {
            errorCode = YouQuanService.OP_NETWORK_ERR;
            errorMsg = "网络错误";
            return YouQuanService.OP_NETWORK_ERR;
        }
        JSONArray feedsArray = JSON.parseObject(feedsJson).getJSONArray("feeds");
        if (null == feedsArray) {
            errorCode = YouQuanService.OP_SERVER_DENY_ERR;
            errorMsg = "获取话题失败！";
            return YouQuanService.OP_SERVER_DENY_ERR;
        }
        //获得话题
        for (int i = 0; i < feedsArray.size(); i++) {
            JSONObject json = feedsArray.getJSONObject(i);
            map.clear();

            map.put("content", json.getString("body"));

            SimpleDateFormat sf = new SimpleDateFormat(TIME_FORMAT, Locale.CHINA);
            Long lastRefefreshTime;
            try {
                lastRefefreshTime = sf.parse(json.getString("createdAt")).getTime();
            } catch (ParseException e) {
                lastRefefreshTime = 0L;
            }
            map.put("publishTime", lastRefefreshTime.toString());
            JSONArray attachments= json.getJSONArray("attachments");
            for (int j=0;j<attachments.size();i++){
                JSONObject attach = attachments.getJSONObject(i);
                map.put("imgUri_"+i+1, attach.getString("url"));
            }

            map.put("lat", json.getLong("latitude").toString());
            map.put("lng", json.getLong("longitude").toString());
            BDLocation location = new BDLocation();
            location.setLongitude(json.getLong("longitude"));
            location.setLatitude(json.getLong("latitude"));
            map.put("locationStr", location.getProvince()+"/"+location.getCity()+"/"+location.getDistrict()+"/"+location.getStreet());
            //User owner 根据owerid去绑定吧，
            list.add(map);
        }
        return YouQuanService.OP_SUCCESS;
    }

    private int parseContactsJson(String contantsJson) {
        list.clear();
        if (YouQuanStringHelper.isEmptyOrNull(contantsJson)) {
            errorCode = YouQuanService.OP_NETWORK_ERR;
            errorMsg = "网络错误";
            return YouQuanService.OP_NETWORK_ERR;
        }
        JSONArray jsonArray = JSON.parseObject(contantsJson).getJSONArray("users");
        if (null == jsonArray) {
            errorCode = YouQuanService.OP_SERVER_DENY_ERR;
            errorMsg = "获取联系人失败！";
            return YouQuanService.OP_SERVER_DENY_ERR;
        }
        //获得联系人
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject contantJson = jsonArray.getJSONObject(i);
            if (parsePersonalJson(contantJson.toJSONString()) == YouQuanService.OP_SUCCESS) {
                list.add(new HashMap<String, String>(map));
            } else {
                errorCode = YouQuanService.OP_SERVER_DENY_ERR;
                errorMsg = "获取联系人失败!";
                return YouQuanService.OP_SERVER_DENY_ERR;
            }
        }
        return YouQuanService.OP_SUCCESS;
    }

    //解析登录页面带回的参数
    private int parseLoginJson(String loginJson) {
        if (YouQuanStringHelper.isEmptyOrNull(loginJson)) {
            errorCode = YouQuanService.OP_NETWORK_ERR;
            errorMsg = "网络错误";
            return YouQuanService.OP_NETWORK_ERR;
        }
        JSONObject json = JSON.parseObject(loginJson);
        if (null == json) {
            errorCode = YouQuanService.OP_SERVER_DENY_ERR;
            errorMsg = "用户登录认证失败！";
            return YouQuanService.OP_SERVER_DENY_ERR;
        }
        //设置token
        this.setToken(json.getString("token"));
        //获取用户id
        Long id = JSON.parseObject(json.getString("user")).getLong("id");
        if (null == id) {
            return YouQuanService.OP_SERVER_DENY_ERR;
        }
        map.put("id", String.valueOf(id));
        return YouQuanService.OP_SUCCESS;
    }

    //解析根据ID获取的用户信息
    private int parsePersonalJson(String personJson) {
        map.clear();
        if (YouQuanStringHelper.isEmptyOrNull(personJson)) {
            errorCode = YouQuanService.OP_NETWORK_ERR;
            errorMsg = "网络错误";
            return YouQuanService.OP_NETWORK_ERR;
        }

        JSONObject json = JSON.parseObject(personJson);
        if (null == json) {
            errorCode = YouQuanService.OP_SERVER_DENY_ERR;
            errorMsg = "用户登录认证失败！";
            return YouQuanService.OP_SERVER_DENY_ERR;
        }

        map.put("username", json.getString("nickname"));
        map.put("userPhone", JSON.parseObject(json.getString("phone")).getString("phoneNumber"));
        map.put("name", json.getString("username"));
        try {
            map.put("pinyinName", YouQuanPinyinHelper.getPingYin(json.getString("username")));
        } catch (Exception e) {
            map.put("pinyinName", "");
        }

        map.put("iconUri", json.getString("avatar"));
        map.put("bgImgUri", json.getString("avatar"));
        map.put("selfIntroduction", json.getString("introduction"));
        map.put("lat", json.getLong("latitude").toString());
        map.put("lng", json.getLong("longitude").toString());

        SimpleDateFormat sf = new SimpleDateFormat(TIME_FORMAT, Locale.CHINA);
        Long lastRefefreshTime;
        try {
            lastRefefreshTime = sf.parse(json.getString("updatedAt")).getTime();
        } catch (ParseException e) {
            lastRefefreshTime = 0L;
        }

        map.put("lastRefreshTime", lastRefefreshTime.toString());

        return YouQuanService.OP_SUCCESS;
    }

    //获取token值
    public String getToken() {
        return this.token;
    }

    //设置token
    private void setToken(String token) {
        this.token = token;
    }

}
